package com.fast.admin.controller;

import cn.hutool.core.util.RandomUtil;
import com.fast.admin.utils.EsUtils;
import com.fast.common.db.mapper.po.User;
import com.fast.common.web.annotation.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : TWL
 * @createTime : 2024/10/7 12:49
 */
@Slf4j
@RestController
@ResponseResult
@RequestMapping("es")
public class ESController {

    @Autowired
    EsUtils esUtils;

    @GetMapping("test")
    public String test() throws IOException {
        if (esUtils.hasIndex("test")) {
//            return "已存在";
        }
//        esUtils.createIndex("test");
        esUtils.deleteDocument("test", "1");
        return "创建";
    }

    @GetMapping("test2")
    public boolean test2() throws IOException {
        String name="test1";
        if (!esUtils.hasIndex(name)) {
            esUtils.createIndex(name);
        }
        User user = new User();
        Long b = RandomUtil.randomLong();
        user.setId(4632130335695027044l);
        user.setKey("d");
        user.setEmail("e");
        user.setName("测试");
        return esUtils.insertDocument(name, user, String.valueOf(b));
    }

    @GetMapping("test3")
    public Object test3() throws IOException {
        String name = "test1";
        if (!esUtils.hasIndex(name)) {
            esUtils.createIndex(name);
        }
        for (int i = 0; i < 1000000; i++) {

            User user = new User();
            Long b = RandomUtil.randomLong();
            user.setId(b);
            user.setKey("d" + b);
            user.setEmail("e" + b);
            user.setName("测试" + b);
            user.setName("测试" + b);
            esUtils.insertDocument(name, user, String.valueOf(b));
            Map<String, Integer> search = esUtils.search(name);

            if (search.get("idcount") > search.get("count")) {
                System.out.println(search.get("idcount") + " 唯一>总数 " + search.get("count"));
                break;
            }
        }
//

        return "bb";
    }

    @GetMapping("test4")
    public Map<String,Object> test4() {

        String name="test1";

        Integer test1 = esUtils.count(name);

        Map<String, Integer> search = esUtils.search(name);


        Map<String,Object> map = new HashMap<>();
        map.put("索引下的总条数",test1);
        map.put("总数统计", search.get("count"));
        map.put("去重统计",search.get("idcount"));
        map.put("terms",search.get("trams"));


        return map;
    }
}
